package com.aij.starter.api;

import java.io.IOException;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

public class HttpApiClient {
	/**
	 * POST(对象参数)
	 * @param url
	 * @param param
	 */
	public String doPost(String url, Object param) {
		// 获得Http客户端
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		String jsonString = JSON.toJSONString(param);
		StringEntity entity = new StringEntity(jsonString, "UTF-8");
		httpPost.setEntity(entity);
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 取响应的结果
			int statusCode = response.getStatusLine().getStatusCode();
			// 打印响应结果
			if (statusCode == HttpStatus.SC_OK) {
			    String resp = EntityUtils.toString(response.getEntity(), "utf-8");
			    return resp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
